package dynamicprogramming.编辑距离;

public class Solution {

    public int minDistance(String word1, String word2) {
        /**
         * intention
         * execution
         * f[i][j] 表示 word1[0-i] 变化为 word2[0-j]需要的最小次数
         * 则f[i][j]：
         * if word1.equals(word2) f[i][j] = 0 ;
         * else if word1[i] == word2[j]  f[i][j] = f[i-1][j - 1 ]
         * else f[i][j] = Math.min(Math.min(f[i - 1][j], f[i][j - 1]), f[i - 1][j - 1]) + 1
         * 插入：dp[i][j-1] + 1 - 在 word1 中插入一个字符
         * 删除：dp[i-1][j] + 1 - 从 word1 中删除一个字符
         * 替换：dp[i-1][j-1] + 1 - 替换 word1 中的一个字符
         */
        if (word1.equals(word2)) {
            return 0;
        }
        int len1 = word1.length();
        int len2 = word2.length();
        int[][] f = new int[len1 + 1][len2 + 1];
        for (int i = 0; i <= len1; i++) {
            f[i][0] = i;
        }
        for (int i = 0; i <= len2; i++) {
            f[0][i] = i;
        }
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    f[i][j] = f[i - 1][j - 1];
                } else {
                    f[i][j] = Math.min(Math.min(f[i - 1][j], f[i][j - 1]), f[i - 1][j - 1]) + 1;
                }
            }
        }
        return f[len1][len2];
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.minDistance("intention", "execution"));
    }
}
